// components/ErrorPage.tsx
import { useRouteError, isRouteErrorResponse, Link } from "react-router-dom";

export default function ErrorPage({
  errorTitle,
  errorMessage,
}: {
  errorTitle: string;
  errorMessage: string;
}) {
  return (
    <div
      id="error-page"
      className="px-10 py-5 text-center max-w-[600px] my-0 mx-auto"
    >
      <h1 className="mb-5" style={{ color: "#ff4757" }}>
        {errorTitle}
      </h1>
      <p className="text-lg mb-8">
        <i>{errorMessage}</i>
      </p>

      {/* 特别处理 StoreProvider 错误 */}
      {errorMessage.includes("StoreProvider") && (
        <div className="bg-[#fff3cd] p-4 rounded-lg mb-5 border border-solid border-[#ffeaa7]">
          <p className="m-0 text-[#856404]">
            <strong>Store 配置错误：</strong>请检查组件是否在 StoreProvider
            内部使用
          </p>
        </div>
      )}

      <div>
        <Link
          to="/"
          style={{
            display: "inline-block",
            padding: "10px 20px",
            background: "#1890ff",
            color: "white",
            textDecoration: "none",
            borderRadius: "6px",
            marginRight: "10px",
          }}
        >
          返回首页
        </Link>
        <button
          onClick={() => window.location.reload()}
          style={{
            padding: "10px 20px",
            background: "#52c41a",
            color: "white",
            border: "none",
            borderRadius: "6px",
            cursor: "pointer",
          }}
        >
          重新加载
        </button>
      </div>
    </div>
  );
}

export function RouterErrorPage() {
  const error = useRouteError();

  console.error("Router error:", error);

  let errorMessage: string;
  let errorTitle: string = "出了点问题";

  if (isRouteErrorResponse(error)) {
    // React Router 错误
    errorTitle = `${error.status} ${error.statusText}`;
    errorMessage = error.data?.message || "页面加载失败";
  } else if (error instanceof Error) {
    // JavaScript 错误
    errorTitle = "应用程序错误";
    errorMessage = error.message;
  } else {
    // 未知错误
    errorTitle = "未知错误";
    errorMessage = "发生了未知错误";
  }

  return <ErrorPage errorTitle={errorTitle} errorMessage={errorMessage} />;
}
